package resources;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Files {

	private PriorityQueue<File> files;

	// CONSTRUCTOR

	public static ArrayList<File> getFilesUnder(File file) {
		return new Files(file).getFiles();
	}

	private Files(File file) {
		files = new PriorityQueue<File>(1, new Comparator<File>() {

			public int compare(File f1, File f2) {
				int out = 0;
				// by extension
				out = getExtension(f1).compareTo(getExtension(f2));
				if (out != 0)
					return out;
				// by order
				out = getOrder(f1).compareTo(getOrder(f2));
				if (out != 0)
					return out;
				//
				return 0;
			};
		});
		recurse(file);
	}

	public void add(File file) {
		recurse(file);
	}

	private void recurse(File file) {
		if (file.isFile())
			files.add(file);
		else if (file.isDirectory())
			for (File f : file.listFiles())
				recurse(f);
		else if (!file.exists())
			for (File f : file.getParentFile().listFiles())
				if (getPureName(f).equals(getPureName(file)))
					recurse(f);
	}

	// GETTERS

	private ArrayList<File> getFiles() {
		ArrayList<File> out = new ArrayList<File>();
		while (!files.isEmpty())
			out.add(files.remove());
		return out;
	}

	// STATIC

	private static String getPureName(String name) {
		int end = name.lastIndexOf(".");
		if (end == -1)
			end = name.lastIndexOf("_");
		else if (name.lastIndexOf("_") != -1)
			end = Math.min(name.lastIndexOf("."), name.lastIndexOf("_"));
		return (end == -1) ? name : name.substring(0, end);
	}

	private static boolean isSubFile(String fileName, String subFileName) {
		return false;
	}

	private static String getExtension(String name) {
		int end = name.lastIndexOf(".") + 1;
		return name.substring(end);
	}

	private static Double getOrder(String name) {
		int end = name.lastIndexOf(".");
		try {
			return new Double(name.substring(name.lastIndexOf("_") + 1, (end == -1) ? name.length() : end));
		} catch (NumberFormatException e) {}
		return new Double(0);
	}

	public static String getPureName(File file) {
		return getPureName(file.getName());
	}

	public static String getExtension(File file) {
		return getExtension(file.getName());
	}

	public static Double getOrder(File file) {
		return getOrder(file.getName());
	}

}
